<?php
/**
 * Created by PhpStorm.
 * User: ZD-SERVER
 * Date: 2017/7/28
 * Time: 11:25
 */

/**
 * Class request
 *
 */
class request{
    private $arr;
    private $sentTime=0;
    private $checkInterval=2;
    private $path="d:/cLOG.txt";
    private $sendInterval;
    private $times;
    private $fun;
    private $config=[];
    public function setSentTime($sTime){
        $this->sentTime=strtotime($sTime);
    }

    private function readConfig(){
        $json_string = file_get_contents('config.php');
        $this->config = json_decode($json_string, true);// 把JSON字符串转成PHP数组
    }
    private function setConfig($key,$value){
        $this->config[$key]=$value;
        $json_string = json_encode($this->config);
        file_put_contents("config.php",$json_string);// 写入文件

    }

    private function excute(){
        $a=$this->fun;
        $a($this->arr);
    }

    /**
     * request constructor.
     * @param $sTime string "2017-07-29 18:15:00"
     * @param  $arr addAddress=>收件人 Body=>内容 Subject=>主题
     */
    public function __construct($sTime,$function,$arr,$sendInterval=60,$times=PHP_INT_MAX)
    {
        $this->fun=$function;
        $this->arr=$arr;
        $this->setSentTime($sTime);
        $this->sendInterval=$sendInterval;
        $this->times=$times;
    }

    public function start(){

        $this->readConfig();
        $this->setConfig("continue",1);

        ignore_user_abort(0);
        set_time_limit(0);

        global $count;
        $count=0;
        $countMail=1;
        while (true ){
            $count++;
            file_put_contents($this->path,$count."\n",FILE_APPEND);


            $this->readConfig();
            $continue=$this->config["continue"];

            if(!$continue){
                $msg= "Stopped by someone";
                file_put_contents($this->path,$msg."\n",FILE_APPEND);
                die("<br>Stopped");
            }
            $now=time();
            if($now>$this->sentTime){


//                var_dump( date("Y m d , H i s", $this->sentTime));
                $this->sentTime+=$this->sendInterval;
//                $this->arr['Subject'].=$countMail;
//                var_dump( date("Y m d , H i s", $this->sentTime));
                $this->excute();
                $countMail++;
                if ($countMail>$this->times)
                    die("<br>all Mail  sent");
                file_put_contents($this->path,date("H:i:s")."==>$countMail\n",FILE_APPEND);
            }else{
                file_put_contents($this->path,date("H:i:s",$now)."==>".date("H:i:s",$this->sentTime)."\n",FILE_APPEND);
            }


            sleep($this->checkInterval);


        }


    }


}